//
//  IdentityInfoViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/11/1.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "IdentityInfoViewController.h"
#import "SC_ActionSheet.h"
#import "LCAFRequestHost.h"
#import <AliyunOSSiOS/OSSService.h>
#import "IdentityCell.h"
#import "IdentityModel.h"
#import "LcButton.h"
#import "FootView.h"
@interface IdentityInfoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,assign)NSInteger index; //上传图片索引
@property (nonatomic,strong)OSSClient *client;
@property (nonatomic,strong)NSString *bucketname;
@property (nonatomic,strong)UIImage *photo;
@property(nonatomic,strong)UITableView * tableView;
@property(nonatomic,strong)NSMutableArray * dataArray;
@property (nonatomic,strong)NSString *urlStr1;
@property (nonatomic,strong)NSString *urlStr2;
@property (nonatomic,strong)NSString *urlStr3;
@property (nonatomic,strong)LcButton * submitbutton;
@property (nonatomic,strong)FootView * footView;
@end

@implementation IdentityInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _index = 10086;
    [self getData];
    [self setOSS];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.submitbutton];
   
    
}
- (void)getData
{
    _urlStr1 =@"";
    _urlStr2 =@"";
    _urlStr3 =@"";
    for (int i=0; i<_imgArray.count; i++)
    {
        NSDictionary * dic = _imgArray[i];
        if ([dic[@"type"] integerValue]==0)
        {
            _urlStr1 = dic[@"value"];
        }else if ([dic[@"type"] integerValue]==1)
        {
            _urlStr2 = dic[@"value"];
        }else if ([dic[@"type"] integerValue]==2)
        {
            _urlStr3 = dic[@"value"];
        }
    }
    NSArray * array;
    if ([_country_code isEqualToString:@"AU"] ||_country_id.integerValue ==13) //澳大利亚
    {
        array = @[@{@"photoTitle":Localized(@"Authentication_uploading_zheng1_message"),@"title":Localized(@"set_ID_certification"),@"contont":Localized(@"Authentication_ID_Photo"),@"image":_urlStr1},
                  @{@"photoTitle":Localized(@"Authentication_uAddress_proof_photo"),@"title":Localized(@"Authentication_uAddress_proof"),@"contont":Localized(@"Authentication_uAddress_proof_message"),@"image":_urlStr2},
                  @{@"photoTitle":Localized(@"Authentication_autograph"),@"title":Localized(@"Authentication_autograph_title"),@"contont":Localized(@"Authentication_autograph_contont"),@"image":_urlStr3}];
       
        
    }else
    {
        
         NSString * content = [NSString stringWithFormat:Localized(@"Authentication_message"),[AppDelegate shareAppdelegate].name];
        array = @[@{@"photoTitle":Localized(@"Authentication_uploading_zheng1_message"),@"title":Localized(@"set_ID_certification"),@"contont":Localized(@"Authentication_uploading_zheng_message"),@"image":_urlStr1},
                  @{@"photoTitle":Localized(@"Authentication_uploading_shengmingshu_message"),@"title":Localized(@"Authentication_Statement_photo_message1"),@"contont":content,@"image":_urlStr2},
                  ];
    }
    
    for (NSDictionary * dic in array)
    {
        IdentityModel * modle = [[IdentityModel alloc] init];
        modle.photoTitle = dic[@"photoTitle"];
        modle.title = dic[@"title"];
        modle.contont = dic[@"contont"];
        modle.iamgeStr = dic[@"image"];
        [self.dataArray addObject:modle];
    }
    [self.tableView reloadData];
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight - kStatusBarAndNavigationBarHeight - 60)];
      
        _tableView.separatorColor = CELLCOLOR;
        _tableView.backgroundColor = TABLEVIEWLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[IdentityCell class] forCellReuseIdentifier:@"IdentityCell"];
        _tableView.tableFooterView = self.footView;
    }
    return _tableView;
}
- (FootView *)footView
{
    if (!_footView) {
        if ([_country_code isEqualToString:@"AU"] ||_country_id.integerValue ==13) //澳大利亚
        {
            _footView = [[FootView alloc] initWithisAU:YES];
        }else
        {
             _footView = [[FootView alloc] initWithisAU:NO];
        }
        
    }
    return _footView;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (LcButton *)submitbutton
{
    if (!_submitbutton) {
        _submitbutton = [[LcButton alloc] initWithFrame:CGRectMake(15, UIScreenHeight - 60 - kStatusBarAndNavigationBarHeight, UIScreenWidth -30, 40)];
        [_submitbutton setTitle:Localized(@"Authentication_subimt_info") forState:0];
        _submitbutton.backgroundColor = TABTITLECOLOR;
        [_submitbutton addTarget:self action:@selector(submitbutton:) forControlEvents:UIControlEventTouchUpInside];
         KViewRadius(_submitbutton, 2);

    }
    return _submitbutton;
}
#pragma  mark -----tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    IdentityCell *cell = (IdentityCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];

    return cell.conton.height + 280;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    IdentityCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"IdentityCell"];

    cell.model=_dataArray[indexPath.row];
    if (indexPath.row ==_index) {
        cell.bgphoto.image = _photo;
    }
    WeakSelf
    cell.upPhotoBlock = ^{
        
         [weakSelf upPhotoWithindexPath:indexPath];
        
    };
    return cell;
    
}
- (void)upPhotoWithindexPath:(NSIndexPath *)indexPath
{
    _index = indexPath.row;
    [self uploadImage];
}
/*OSS上传图片设置*/
- (void)setOSS
{
    WeakSelf
    [self GETWithHost:@"" path:ossAuth param:@{} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue] ==0)//成功
        {
            NSDictionary * dic = responseObject[@"result"];
            NSDictionary * credentials = dic[@"credentials"];
            NSString *endpoint = dic[@"endpoint"];
            self.bucketname = dic[@"bucket"];
            id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:credentials[@"access_key_id"] secretKeyId:credentials[@"access_key_secret"] securityToken:credentials[@"security_token"]];
            
            weakSelf.client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
        }
        
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
/*提交*/
- (void)submitbutton:(LcButton *)sender {
    if ([NSString isEmptyString:_urlStr1]) {
        if ([_country_code isEqualToString:@"AU"] ||_country_id.integerValue ==13) //澳大利亚
        {
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_autograph_photo") view:kWindow];
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_Statement_photo_document_message") view:kWindow];
        }
        
        [sender stopAnimation];
        return;
    }
    if ([NSString isEmptyString:_urlStr2]) {
        if ([_country_code isEqualToString:@"AU"] ||_country_id.integerValue ==13) //澳大利亚
        {
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_autograph_address_photo") view:kWindow];
            
        }else
        {
           [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_document_message") view:kWindow];
        }
        
        [sender stopAnimation];
        return;
    }
    if ([_country_code isEqualToString:@"AU"] ||_country_id.integerValue ==13) //澳大利亚
    {
        if ([NSString isEmptyString:_urlStr3]) {
            
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_Signature_photo") view:kWindow];
            [sender stopAnimation];
            return;
        }
    }
    
    [self POSTWithHost:@"" path:confirmIdentity param:@{@"id":_identity_id} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] ==0)//成功
        {
            [sender stopAnimation];
            [self.navigationController popToRootViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter]postNotificationName:VerificationSusessNotificationse object:nil];
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_subimt_sucess") view:kWindow];
            
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)uploadImage
{
    WeakSelf
    SC_ActionSheet *sheet = [[SC_ActionSheet alloc]initWithFirstTitle:Localized(@"Authentication_Photograph_message") secondTitle:Localized(@"Authentication_albums_message")];
    sheet.selectedSth = ^(NSInteger tag) {
        
        
        switch (tag) {
            case 0:
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    
                    UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
                    imagePicker.delegate = self;
                    imagePicker.allowsEditing = NO;
                    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    [weakSelf presentViewController:imagePicker animated:YES completion:nil];
                }
                break;
            case 1:
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                    UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
                    imagePicker.delegate = self;
                    imagePicker.allowsEditing = NO;
                    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                    [weakSelf presentViewController:imagePicker animated:YES completion:nil];
                }
                break;
            default:
                break;
        }
        
    };
    [sheet show];
}
#pragma mark 调用系统相册及拍照功能实现方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    UIImage * chosenImage = info[UIImagePickerControllerOriginalImage];
    
    //    chosenImage = [self imageWithImageSimple:chosenImage scaledToSize:CGSizeMake(400, 400)];
    
    
    
    //将图片上传到服务器
    
    [picker dismissViewControllerAnimated:YES completion:^{
        NSData * imageData = UIImageJPEGRepresentation(chosenImage, 1.0);
        [self uploadossimagedata:imageData image:chosenImage];
    }];
    
}

//上传图片
-(void)uploadossimagedata:(NSData*)data image:(UIImage *)image
{
    //显示加载标题
    [SVProgressHUD showWithStatus:Localized(@"Authentication_uploading_message")];
    //设置HUD和文本的颜色
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    //设置HUD背景颜色
    [SVProgressHUD setBackgroundColor:BLACKCOLOR];
    [SVProgressHUD setDefaultAnimationType:(SVProgressHUDAnimationTypeFlat)];
    
    
    
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName =self.bucketname;
    put.objectKey = [self getTimeNow];
    put.uploadingData = data; // 直接上传NSData
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [_client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSString *object = put.objectKey;
            [self uploadImageWihtimageFile:object image:image];
        } else {
            [SVProgressHUD dismiss];
            [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Authentication_uploading_error_message") view:kWindow];
        }
        return nil;
    }];
    //     可以等待任务完成
    //    [putTask waitUntilFinished];
    
}
- (void)uploadImageWihtimageFile:(NSString *)file image:(UIImage *)image
{
    WeakSelf
    [self POSTWithHost:@"" path:uploadImage param:@{@"identity_id":self.identity_id,@"filename":file,@"img_type":@(_index)} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        if ([responseObject[@"code"] integerValue] ==0)//成功
        {
            weakSelf.photo = image;
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:weakSelf.index inSection:0];
            [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            switch (weakSelf.index) {
                case 0:
                    weakSelf.urlStr1=@"0";
                    break;
                case 1:
                    weakSelf.urlStr2=@"1";
                    break;
                case 2:
                    weakSelf.urlStr3=@"2";
                    break;
                    
                default:
                    break;
            }
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            [[NSNotificationCenter defaultCenter] postNotificationName:SubimtVerificationDataNotificationse object:nil];
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }

    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}
//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
/**
 *  返回当前时间用来上传图片的时间戳
 *
 *  @return getTimeNow
 */
-(NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@%i.jpg", date,last];
    NSLog(@"%@.jpg", timeNow);
    NSString *userId = [EXUserManager personalData].id;
    if ([NSString isEmptyString:userId]) {
        userId = @"";
    }
    userId = [userId stringByAppendingString:timeNow];
    return userId;
}

@end
